-- 时钟1kHz, reset, 每隔1s三个led灯轮流亮


library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity led is
    port(
        clk : in std_logic;
        reset : in std_logic;
        q3, q2, q1 : out std_logic;
        clkout : out std_logic
    );
end led;

architecture behave of led is
    type state_type is (s0, s1, s2, s3);    -- 全熄，三个灯亮状态
    signal state : state_type;
    signal count : std_logic_vector(9 downto 0);
    signal clkout_tmp : std_logic;
    signal q : std_logic_vector(2 downto 0);
begin

    process(reset, clk) begin
        if reset = '1' then
            chout_tmp <= '0';
            count <= '0';
        elsif clk'event and clk = '1' then
            if count <= "1111100111" then   -- 999
                count <= count + 1;
            else
                count <= (others => '0');
            end if;

            if count = "1111100111" then 
                clkout_tmp <= not clout_tmp;
            end if;
        end if;
    end process;

    process(reset, clout_tmp) begin
        if reset = '1' then
            state <= '0';
            q <= (others => '0');
        elsif clout_tmp'event and clout_tmp = '1' then
            case state is
                when s0 => state <= s1; q <= "000";
                when s1 => state <= s2; q <= "001";
                when s2 => state <= s3; q <= "010";
                when s3 => state <= s0; q <= "100";  
            end case;
        end if;
    end process;

    q3 <= q(2);
    q2 <= q(1);
    q1 <= q(0);
    clkout <= clkout_tmp;
end behave;